<template>
  <view>
    <form>
      <!-- <view class="cu-card margin radius">
        <view class="cu-form-group">
          <view class="title">工程编号</view>
          <view>{{ dataInfo.projectno }}</view>
        </view>
        <view class="cu-form-group">
          <view class="title xm-title">工程名称</view>
          <view class="sub-title">{{ dataInfo.projectname }}</view>
        </view>
      </view> -->
      <xmInfo
      :projectno="dataInfo.projectno"
      :projectname="dataInfo.projectname"
    ></xmInfo>

      <view class="cu-form-group">
        <view class="title"
          ><text class="cuIcon-favorfill text-xs text-red"></text>开始日期</view
        >
        <picker
          mode="date"
          :value="dataInfo.starttime ? dataInfo.starttime : date"
          :start="date"
          :disabled="!id ? false : true"
          @change="DateChange('starttime', $event)"
        >
          <view class="picker">
            {{ dataInfo.starttime ? dataInfo.starttime : "请选择开始日期" }}
          </view>
        </picker>
      </view>
	  
	  <view class="cu-form-group ">
	      <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>延期天数</view>
	      <view style="flex: 1;">
	  		<u-input :disabled="!id ? false : true" @input="delaydayChange" placeholder="请输入施工时间" v-model="dataInfo.delayday" type="number" maxlength="200" ></u-input>
	  	</view>
	  </view>
	  
	  
      <view class="cu-form-group">
        <view class="title"
          ><text class="cuIcon-favorfill text-xs text-red"></text>结束日期</view
        >
        <picker
          mode="date"
          :start="date"
          :value="dataInfo.endtime ? dataInfo.endtime : date"
          :disabled="true"
          @change="DateChange('endtime', $event)"
        >
          <view class="picker">
            {{ dataInfo.endtime ? dataInfo.endtime : "请选择结束日期" }}
          </view>
        </picker>
      </view>
      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white">
        <view class="action"
          >佐证图片</view
        >
      </view>
      <view class="cu-form-group">
        <js-uploadfile
          v-model="dataInfo.dataMap"
          :biz-key="dataInfo.id"
          biz-type="PmDelay_image"
          :deletable="!!id ? false : true"
          :customBtn="!id ? false : true"
        ></js-uploadfile>
      </view>
      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white">
        <view class="action"
          ><text class="cuIcon-favorfill text-xs text-red"></text>延期原因</view
        >
      </view>
      <view class="cu-form-group" v-if="!id">
        <textarea
          maxlength="-1"    
          v-model="dataInfo.remarks"
		  :disabled="!id ? false : true"
          @input="textareaAInput"
          placeholder="请输入延期原因"
        ></textarea>
      </view>
      <view class="cu-form-group" v-if="!!id">
        {{ dataInfo.remarks }}
      </view>
      <!-- <view class="cu-form-group pre-wrap" v-if="!!id">
        {{ dataInfo.remarks }}
      </view> -->
      <!-- <view class="cu-form-group" v-if="!!dataInfo.delayday">
        <view class="title xm-title">延期天数</view>
        <view class="sub-title">{{ dataInfo.delayday }}</view>
      </view> -->
      <view class="cu-form-group" v-if="!!dataInfo.createByName">
        <view class="title xm-title">申请人</view>
        <view class="sub-title">{{ dataInfo.createByName }}</view>
      </view>
      <view class="cu-form-group" v-if="!!dataInfo.createDate">
        <view class="title xm-title">申请时间</view>
        <view class="sub-title">{{ dataInfo.createDate }}</view>
      </view>

      <!-- <file-upload
        :uploadOptions="uploadOptions"
        :imgList="dataInfo.dImageList"
        @imgListChange="imgListChange"
      ></file-upload> -->
      <view class="cu-form-group" style="min-height: 0"></view>

      <view style="height: 80px"></view>
      <view class="btn-group cu-bar foot cu-bar1">
        <!-- <button class="cu-btn bg-green shadow-blur">提交</button> -->
        <view class="flex">
          <js-bpm-button
            v-model="dataInfo.bpm"
            :biz-key="dataInfo.id"
            form-key="Flow_Delay"
            :showTraceText="showTraceText"
            @complete="submit"
          ></js-bpm-button>
        </view>
        <!-- <view class="flex" v-else-if="!dataInfo.id">
          <js-bpm-button
            v-model="dataInfo.bpm"
            :biz-key="dataInfo.id"
            form-key="Flow_Delay"
            @complete="submit"
          ></js-bpm-button>
        </view> -->
      </view>
    </form>
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: {
    xmInfo,
  },
  data() {
    return {
      uploadOptions: {},
      // date: new Date().toISOString().substring(0, 10),
      date: '',
      modalName: null,
      modalNameDetail: null,
      showAddDetail: false,
      dataInfo: {
        id: "",
        bpm: {},
      },
      isSubmitting: false,
      showButton: true,
      // flag: hasPermission('process:pressure:pmPressuretest:edit'),
      id: "",
      dataInfoRemarks:' ',
      bpmTaskId:'',
      showTraceText: true,
      // addflag : hasPermission('process:delay:pmDelay:add'),
      // editflag : hasPermission('process:delay:pmDelay:edit')
    };
  },

  onLoad(e) {
	    this.$u.api.zfgs.getAllowDelays().then((res) => {
			var today = new Date();
			today.setDate(today.getDate() - res.data);
			this.date = today.toLocaleDateString();
		})
	 
    console.log(this.date,'this.date=======---');
    console.log(e,'延期豁免---');
    if (!!e.id) {
      this.showButton = true;
      this.getDelayPmDelayForm(e.id);
      this.id = e.id;
   //    this.bpmTaskId = e['bpm.procInsId'];
   //    if (!this.bpmTaskId) {
   //        this.showTraceText = false;
			// }
    }
    if (!!e.xm) {
      this.showButton = true;
      this.dataInfo = JSON.parse(e.xm);
      //   巡检人
      this.dataInfo.checkdate = this.date;
      this.dataInfo.state = 1;
      this.dataInfo.inspector = this.vuex_user.userName;
      this.dataInfo.state = 4;
    }

    console.log(this.dataInfo.bpm, 'this.dataInfo.bpm');
  },

  methods: {
    submit() {
      if (!this.dataInfo.starttime) {
        this.$u.toast("开始时间必填");
        return;
      }
      if (!this.dataInfo.endtime) {
        this.$u.toast("结束时间必填");
        return;
      }
      // if (!this.dataInfo.dataMap || !this.dataInfo.dataMap.PmDelay_image) {
      //   this.$u.toast("佐证图片必传");
      //   return;
      // }
      if (!this.dataInfo.remarks) {
        this.$u.toast("延期原因必填");
        return;
      }
      if (this.isSubmitting) {
        return;
      } else {
        this.isSubmitting = true;
        try {
			this.dataInfo.status = 4;
          this.$u.api.zfgs.delayPmDelaySave(this.dataInfo).then((res) => {
            if (res.result == "true") {
              this.$u.toast(res.message);
              const itemContent = {
                projectno: this.dataInfo.projectno,
                projectname: this.dataInfo.projectname,
              };
              setTimeout(() => {
                // uni.navigateTo({
                //   url:
                //     "/pages/zfgs/process/delay/pmDelay/list?item=" +
                //     JSON.stringify(itemContent),
                // });
				uni.navigateBack({
				  delta: 1,
				});
              }, 500);
            } else {
              this.$u.toast(res.message);
            }
          });
        } catch (error) {
          this.$u.toast(error.message);
        } finally {
          this.isSubmitting = false;
        }
      }
    },

    DelItem(items) {
      uni.showModal({
        title: "",
        content: "确定要删除吗？",
        cancelText: "取消",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            // 根据item.zhengGaiNo 查找要删除的项
            // let index = this.dataInfo.rectList.findIndex(
            //   (item) => item.id == items.id
            // );
            this.dataInfo.pmMaterialchecksList.map((item) => {
              if (item.pmid == items.pmid) {
                item.status = 1; //状态为1删除
                // 深度监听dataInfo.rectList
              }
            });
            this.$forceUpdate();
            console.log(this.dataInfo.pmMaterialchecksList);
            this.$u.toast("删除成功");
          }
        },
      });
    },
    getDelayPmDelayForm(id) {
      this.$u.api.zfgs
        .delayPmDelayForm({
          id: id,
        })
        .then((res) => {
          
          this.$nextTick(() => {
            
            this.dataInfo = res.pmDelay;
            console.log('dataInfo.remarks:', this.dataInfo.remarks);
          });
        });
    },
	addDays(startDate, daysToAdd) {
	
	    if (!startDate || !daysToAdd || daysToAdd <= 0){
	      return '';
	    }
	    // 将输入的日期字符串转换为 Date 对象
	    var date = new Date(startDate);
	    
	    // 添加天数
	    date.setDate(date.getDate() + (daysToAdd - 1));
	    
	    // 格式化输出日期
	    function pad(num) {
	        return num < 10 ? '0' + num : num;
	    }
	    
	    var day = pad(date.getDate());
	    var month = pad(date.getMonth() + 1); // 注意月份是从0开始的
	    var year = date.getFullYear();
	    
	    return year + '-' + month + '-' + day;
	},
	delaydayChange(e) {
		
		this.dataInfo.endtime = this.addDays(this.dataInfo.starttime,this.dataInfo.delayday)
	 console.log(this.dataInfo.delayday,'e=====');
	},
    DateChange(item, e) {
      if (item == "starttime") {
        this.dataInfo.starttime = e.detail.value;
		this.dataInfo.endtime = this.addDays(this.dataInfo.starttime,this.dataInfo.delayday)
      } else if (item == "endtime") {
        this.dataInfo.endtime = e.detail.value;
      }

      this.$forceUpdate();
    },
    textareaAInput(e) {
      this.dataInfo.remarks = e.detail.value;
    },
    addDetail() {
      this.showAddDetail = true;

      this.modalNameDetail = "bottomModal";

      console.log(this.modalNameDetail);
    },
    modalNameDetailEmit(e) {
      this.modalNameDetail = e;
    },
    async checkedListEmit(e) {
      console.log(e, "checkedListEmit", this.dataInfo);
      if (this.dataInfo.pmMaterialchecksList == undefined) {
        this.dataInfo.pmMaterialchecksList = [];
      }

      //   创建一个数组eArray，把传递过来的部分属性赋值给eArray
      let eArray = [];
      e.forEach((item) => {
        eArray.push({
          pmid: item.id,
          metercode: item.mcode,
          metername: item.mname,
          mstd: item.mstd,
        });
      });

      if (this.dataInfo.pmMaterialchecksList.length == 0) {
        this.dataInfo.pmMaterialchecksList = eArray;
      } else {
        // 如果this.dataInfo.pmMaterialchecksList不为空数组，则this.dataInfo.pmMaterialchecksList和传递过来的e进行拼接，过滤掉id一样的
        this.dataInfo.pmMaterialchecksList = this.dataInfo.pmMaterialchecksList
          .concat(eArray)
          .filter((item, index, arr) => {
            return arr.findIndex((t) => t.pmid === item.pmid) === index;
          });
      }
    },

    ViewImage(imageList, e) {
      uni.previewImage({
        urls: imageList,
        current: e.currentTarget.dataset.url,
      });
    },
    DelImg(e) {
      uni.showModal({
        title: "",
        content: "确定要删除吗？",
        cancelText: "取消",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            console.log(
              res.confirm,
              this.dataInfo.dImageList,
              e,
              this.dataInfo.dImageList[e.currentTarget.dataset.index]
            );
            // this.dataInfo.dImageListst.splice(e.currentTarget.dataset.index, 1)
            // if (this.dataInfo.dImageListst) {
            //     console.log(e.currentTarget.dataset.index,this.dataInfo.dImageListst,'e====')
            //     this.dataInfo.dImageListst.splice(e.currentTarget.dataset.index, 1);
            // }
            // this.$set(this.dataInfo.dImageListst, e.currentTarget.dataset.index,1)
            // this.dataInfo.dImageListst.splice(e.currentTarget.dataset.index, 1);
            this.$delete(
              this.dataInfo.dImageListst,
              e.currentTarget.dataset.index
            );
          }
        },
      });
    },
    ChooseImage() {
      uni.chooseImage({
        count: 4, //默认9
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album"], //从相册选择
        success: (res) => {
          if (this.dataInfo.dImageList.length != 0) {
            this.dataInfo.dImageListst = this.dataInfo.dImageList.concat(
              res.tempFilePaths
            );
          } else {
            this.dataInfo.dImageList = res.tempFilePaths;
          }

          console.log(this.dataInfo, "this.dataInfo");
          this.$u.toast("上传成功");
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.pre-wrap{
  white-space: pre-wrap;
}
.action {
  color: #303133;
}
.cu-form-group {
  flex-wrap: wrap;
}
.text-sl {
  font-size: 22px !important;
}
.cu-bar1 {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  z-index: 997;
  background: #fff;
}
.green {
  color: green;
}
.input-align {
  text-align: right;
}
.sub-title {
  flex-grow: 1; /* 让右侧内容占据剩余空间 */
  max-width: 200px; /* 或其他合适的最大宽度，超过这个宽度时内容会换行 */
  word-break: break-word; /* 或 overflow-wrap: break-word; 允许单词在必要时断开以适应宽度 */
}
.xm-title {
  flex-basis: 100px; /* 或其他合适的固定宽度，用于左侧标题 */
  flex-shrink: 0; /* 防止标题在小屏幕下收缩 */
  overflow: hidden; /* 可选，防止内容溢出 */
}
.text-xsl {
  font-size: 60rpx !important;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
}
.text-xs {
  font-size: 18rpx !important;
}
</style>